/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.client.gwt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.gadglet.client.gwt.ui.DebugDialogBox;
import com.gadglet.params.SharedConstants;
import com.google.gwt.gadgets.client.GadgetsUtil;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
/**
 * General purpose methods for Gadgets development
 * 
 */
public class GadgetUtils {

	
	
	
	/**
	 * @return true, if the gadget is in "home" view
	 */
	public static boolean isHomeView() {
		boolean homeView = false;

		String currentView = null;

		try {
			currentView = GadgetNativeUtils.getCurrentView();

			if (currentView != null && currentView.equalsIgnoreCase("home"))
				homeView = true;

		} catch (Exception e) {
			return false;
		}

		return homeView;

	}

	/**
	 * @return true, if the gadget is in "canvas" view
	 */
	public static boolean isCanvasView() {
		boolean canvasView = false;

		String currentView = null;

		try {
			currentView = GadgetNativeUtils.getCurrentView();

			if (currentView != null && currentView.equalsIgnoreCase("canvas"))
				canvasView = true;

		} catch (Exception e) {
			return false;
		}

		return canvasView;
	}
	
	/**
	 * @return true, if the gadget is in "profile" view
	 */

	public static boolean isProfileView() {
		boolean profileView = false;

		String currentView = null;

		try {
			currentView = GadgetNativeUtils.getCurrentView();

			if (currentView != null && currentView.equalsIgnoreCase("profile"))
				profileView = true;

		} catch (Exception e) {
			return false;
		}

		return profileView;

	}

	
	
	/**
	 * @return true, if the current user language is Arabic, or Hebrew.
	 */
	public static String getDirection() {

		String direction = null;
		if (GadgetNativeUtils.getLang() != null
				&& (GadgetNativeUtils.getLang().equals("iw") || GadgetNativeUtils
						.getLang().equals("ar")))
			direction = "rtl";
		else
			direction = "ltr";
		return direction;
	}

	
	
	/**
	 * @param isSecure (if https - true, else false)
	 * @return the URL for the gadget server.
	 */
	public static String getGadgetserver(boolean isSecure) {
		DebugDialogBox errorNotifier = DebugDialogBox.getErrorNotifier();
		String serverName = null;
		String serverNamePref = "://";
		int nameStart = 0;
		if (getGadgetXmlUrl().indexOf(serverNamePref) > 0) {
			try {
				nameStart = getGadgetXmlUrl().indexOf(serverNamePref)
						+ serverNamePref.length();
				serverName = getGadgetXmlUrl().substring(nameStart,
						getGadgetXmlUrl().indexOf("/", nameStart));
			} catch (Exception e) {

				errorNotifier.showError(0, e.getMessage());
			}
		} else {
			serverName = SharedConstants.defaultGadgetServer;
		}

		if (isSecure)
			return "https://" + serverName;
		else
			return "http://" + serverName;

	}

	
	/**
	 * @return the name of the gadget as defined on the gadgets server
	 * 
	 */
	public static String getGadgetNameFromXmlUrl() {
		DebugDialogBox errorNotifier = DebugDialogBox.getErrorNotifier();
		String gadgetName = null;
		String gadgetLocation = GadgetUtils.getGadgetXmlUrl();
		try {
			int gadgetNameSart = gadgetLocation
					.indexOf(SharedConstants.gadgetDirName)
					+ SharedConstants.gadgetDirName.length();
			gadgetName = gadgetLocation.substring(gadgetNameSart,
					gadgetLocation.indexOf("/", gadgetNameSart));
		} catch (Exception e) {

			errorNotifier.showError(0, e.getMessage());
		}

		return gadgetName;
	}

	
	/**
	 * @param iconName - the name of the icon, example: "add", "delete", ext. use the default 
	 * icon type (gif). 
	 * @param iconFileName - te full name of the icon: "add.jpg" ext.
	 * @param isSecure - use https url
	 * @return The url for the icon. The icon should be in serverName/static/icons/iconName.gif 
	 */
	public static String getIconURL(String iconName, String iconFileName,
			boolean isSecure) {
		String iconURL = "";

		if (iconName == null && iconFileName == null)
			return iconURL;

		iconURL = getGadgetserver(isSecure);

		if (iconFileName != null)
			iconURL = iconURL + SharedConstants.gadgetIconDirectory + "/"
					+ iconFileName;
		else
			iconURL = iconURL + SharedConstants.gadgetIconDirectory + "/"
					+ iconName + SharedConstants.iconDefaultType;

		return iconURL;
	}
	
	/**
	 * 	Gadget specific icon
	 * @param gadgetName - the name of the gadget
	 * @param iconName - the name of the icon, example: "add", "delete", ext. use the default 
	 * icon type (gif). 
	 * @param iconFileName - te full name of the icon: "add.jpg" ext.
	 * @param isSecure - use https url
	 * @return The url for the icon. The icon should be in serverName/gadgets/gadgetName/static/icons/iconName.gif 
	 */

	public static String getGadgetIconURL(String gadgetName, String iconName,
			String iconFileName, boolean isSecure) {
		String iconURL = "";

		if (gadgetName == null)
			return iconURL;

		if (iconName == null && iconFileName == null)
			return iconURL;

		iconURL = getGadgetserver(isSecure);

		if (iconFileName != null)
			iconURL = iconURL + SharedConstants.gadgetDirName + gadgetName
					+ SharedConstants.gadgetIconDirectory + "/" + iconFileName;
		else
			iconURL = iconURL + SharedConstants.gadgetDirName + gadgetName
					+ SharedConstants.gadgetIconDirectory + "/" + iconName
					+ SharedConstants.iconDefaultType;

		return iconURL;
	}

	/**
	 * 	Gadget specific icon
	 * @param iconName - the name of the icon, example: "add", "delete", ext. use the default 
	 * icon type (gif). 
	 * @param iconFileName - te full name of the icon: "add.jpg" ext.
	 * @param isSecure - use https url
	 * @return The url for the icon. The icon should be in serverName/gadgets/gadgetName/static/icons/iconName.gif 
	 */
	public static String getGadgetIconURL(String iconName, String iconFileName,
			boolean isSecure) {
		GadgetConfig gadgetConfig = GadgetConfig.getGadgetConfig();
		String iconURL = "";
		String gadgetName = null;

		if (gadgetConfig.getGadgetName() != null)
			gadgetName = gadgetConfig.getGadgetName();
		else
			return iconURL;

		if (iconName == null && iconFileName == null)
			return iconURL;

		iconURL = getGadgetserver(isSecure);

		if (iconFileName != null)
			iconURL = iconURL + SharedConstants.gadgetDirName + gadgetName
					+ SharedConstants.gadgetIconDirectory + "/" + iconFileName;
		else
			iconURL = iconURL + SharedConstants.gadgetDirName + gadgetName
					+ SharedConstants.gadgetIconDirectory + "/" + iconName
					+ SharedConstants.iconDefaultType;

		return iconURL;
	}


	/**
	 * @return the name of the gadget hosting app engine instance: ???.appspot.com
	 */
	public static String getProviderName() {
		String name = null;

		name = getGadgetserver(false);
		int start = 0;

		if (name != null) {
			start = name.indexOf("://") + 3;
			return name.substring(name.indexOf("/"), start);
		} else
			return name;
	}


	/**
	 * @return true if hosted on gadglet.appspot.com
	 */
		public static boolean isDefaultServer() {
		if (getProviderName() != null
				&& getProviderName()
						.equals(SharedConstants.defaultGadgetServer))
			return true;
		else
			return false;

	}

		
		
	/**
	 * @return the gadget xml url.
	 */
	public static String getGadgetXmlUrl() {

		String xmlUrl = null;

		xmlUrl = GadgetsUtil.getUrlParameters("url");

		return xmlUrl;
	}

	
	
	/**
	 * set a GWT DialogBox on the top middle of a gadget
	 * @param dialogBox
	 */
	
	public static void dialogBoxTop(DialogBox dialogBox) {
		boolean initiallyShowing = dialogBox.isShowing();
		boolean initiallyAnimated = dialogBox.isAnimationEnabled();

		if (!initiallyShowing) {
			dialogBox.setVisible(false);
			dialogBox.setAnimationEnabled(false);
			dialogBox.show();
		}

		int left = (Window.getClientWidth() - dialogBox.getOffsetWidth()) >> 1;

		dialogBox.setPopupPosition(Math.max(Window.getScrollLeft() + left, 0),
				0);

		if (!initiallyShowing) {
			dialogBox.setAnimationEnabled(initiallyAnimated);
			// Run the animation. The popup is already visible, so we can skip
			// the
			// call to setState.
			if (initiallyAnimated) {
				// impl.setClip(getElement(), "rect(0px, 0px, 0px, 0px)");
				dialogBox.setVisible(true);
				// dialogBox.resizeAnimation.run(ANIMATION_DURATION);
			} else {
				dialogBox.setVisible(true);
			}
		}
	}
	
	
	
	/**
	 * @param params
	 * @return JSON string used in GadgetNativeUtils.requestNavigateToCanvas(String params)
	 * @see GadgetNativeUtils.requestNavigateToCanvas(String params)
	 */
	public static String createJsonParamList(HashMap <String,String> params){
			
		List <String> keys = new ArrayList<String>(params.keySet());
		
		
		int index = 0;
		
		StringBuffer paramList = new StringBuffer();
		paramList.append("({");
		for(String key:keys){
		
			paramList.append("\""+key+"\":\""+params.get(key)+"\"");

			index++;
			
			if(index<keys.size())
				paramList.append(",");
			
		}
		
		paramList.append("})");
		
		return paramList.toString();
		
	}

}
